<?php

namespace App\Http\Controllers\Admin;

use App\Models\Project_admin_role;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class RoleController extends Controller
{
    public function rolePage()
    {
        $role = project_admin_role::all(); //获取所有的角色

        return view('admin.role.role',compact('role'));
    }


    /**
     * 角色管理的修改页面
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editPage($id = 0)
    {
        //修改角色页面
        $role = project_admin_role::find($id);

        return view('admin.role.edit',compact('role'));
    }

    /**
     *角色管理保存或添加
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function createOrSave(Request $request, $id=0)
    {
         $adminRole = project_admin_role::find($id);

        if(!$adminRole){
            $adminRole = new project_admin_role();
            if($adminRole -> existRolename($request)){
                return back() -> with('error','用户名已经存在');
            }

            if($adminRole -> createOrSave($request,0)){
                return redirect()->route('admin.role')->with('success','添加成功');
            }
        }

        if($adminRole -> existRolename($request)){
            return back() -> with('error','用户名已经存在');
        }

        if($adminRole ->createOrSave($request,1)){

            return redirect()->route('admin.role')->with('success','修改成功');
        }

        return back() -> with('error','操作失败');
    }
    /**
     *   角色删除方法
     */
    public function del($id)
    {
        //角色删除方法
       $adminRole =  project_admin_role::find($id);
        if(!empty($adminRole)){
            $adminRole ->delete();
            return redirect(route('admin.role'))->with('success','删除成功');
        }else {
            return back() ->with('error','删除失败');
        }
    }
}
